"use client"
import React, {useEffect, useState} from "react";
import {
    Button,
    Checkbox,
    Col,
    Form,
    Input,
    InputNumber,
    message,
    Modal,
    Radio,
    Row,
    Tooltip, Tree,
} from 'antd';
import { setTreeSelect} from "@/utils/Z";

import styles from "./index.module.css";
import {QuestionCircleOutlined} from "@ant-design/icons";
import {addRole, getRole, updateRole} from "@/clientApi/system/role";
import {
    roleMenuTreeSelect,
    treeselect as menuTreeSelect
} from "@/clientApi/system/menu";
import { globalMessage } from "@/utils/message";

// 定义组件的 props 类型
interface MyComponentProps {
    open: boolean;
    title?: string;
    OnCanCle: () => void;
    roleId?: string|undefined;

}

const EditorRoleView: React.FC<MyComponentProps> = (props) => {
    const [form] = Form.useForm();
    // 表单的值
    const [formData, setFormData] = useState({})
    const [roleOptions, setRoleOptions] = useState([])
    const [checkedKeys, setCheckedKeys] = useState([])
    const [isLeaf, setIsLeaf] = useState(false)


    function handleCancel() {
        props.OnCanCle()
    }

    useEffect(() => {
        if (props.roleId) {
            getRoleMenuTreeSelect(props.roleId);
            getRoleForm(props.roleId)
        } else {
            setCheckedKeys([])
            getMenuTreeSelect()
        }
    }, [props.roleId]);
    const getRoleForm = (id:string):void => {
        getRole(id).then((res:any) => {
            if (res?.code === 200) {
                setFormData(res.data)
                form.setFieldsValue({
                    roleName: res.data?.roleName || '',
                    roleKey: res.data?.roleKey || '',
                    roleSort: res.data?.roleSort || 0,
                    status: res.data?.status || "",
                    menuIds: res.data?.menuIds||[],
                    menuCheckStrictly: res.data?.menuCheckStrictly,
                    remark:res.data?.remark||''
                });
                setIsLeaf(!res.data?.menuCheckStrictly)
            }
        });
    };
    const getRoleMenuTreeSelect = (roleId:string):void => {
        roleMenuTreeSelect(roleId).then((res:any) => {
            if (res?.code === 200) {
                const obj = {
                    key: "id",
                    value: "id",
                    title: "label",
                };
                setRoleOptions(setTreeSelect(res?.menus, obj))
                setCheckedKeys(res?.checkedKeys)
            }
        })
    }
    const getMenuTreeSelect = () => {
        menuTreeSelect().then((res:any) => {
            if (res?.code === 200) {
                const obj = {
                    key: "id",
                    value: "id",
                    title: "label",
                };
                setRoleOptions(setTreeSelect(res?.data, obj))
                form.setFieldsValue({
                    roleName: '',
                    roleKey: '',
                    roleSort:Number(0),
                    status: '0',
                    menuIds: [],
                    menuCheckStrictly: true,
                    remark:''
                });
            }
        });
    }
    const onValuesChange = (changedValues: any, allValues: any) => {
        if (props.roleId !== undefined) {
            setFormData((prevState: any) => ({
                ...prevState, ...changedValues
            }));
        } else {
            setFormData((prevState: any) => ({
                ...allValues
            }));
        }
    };
    const handleSubmit = () => {
        // 在提交前先进行表单验证
        form.validateFields().then((values:any) => {
            setFormData(prevState => ({
                ...prevState,
                ...values
            }));
            if (props.roleId !== undefined) {
                updateRole({...formData,...values}).then((res:any) => {
                     globalMessage().warning(res.msg).then(r => {})
                    props.OnCanCle()
                });
            } else {
                addRole({...formData,...values}).then((res:any) => {
                     globalMessage().warning(res.msg).then(r => {})
                    props.OnCanCle()
                });
            }
        }).catch(errorInfo => {

            // 如果验证失败，则不执行提交操作
        });
    }
    const onCheck = (selectedKeysValue:any):void => {
        if (isLeaf) {
            console.log(selectedKeysValue.checked, isLeaf, 'selectedKeysValue')
            setCheckedKeys(selectedKeysValue.checked);
            form.setFieldsValue({
                menuIds: selectedKeysValue.checked,
            });
        } else {
            setCheckedKeys(selectedKeysValue);
            form.setFieldsValue({
                menuIds: selectedKeysValue,
            });
        }

    };
    const onIsLeaf = (e: { target: { checked: any; }; }):void => {
        setIsLeaf(!e.target.checked)
    };




    return (
        <>
            <Modal
                forceRender
                open={props.open}
                title={props.title}
                footer={null}
                onCancel={() => {
                    props.OnCanCle()
                }}
            >
                <Form
                    form={form}
                    name="editorrole"
                    onValuesChange={onValuesChange}
                    style={{maxWidth: 600}}
                >
                    <Row gutter={10}>
                        <Col span={24}>
                            <Form.Item
                                labelCol={{span: 4,}}
                                label="角色名称"
                                name="roleName"
                                rules={[{required: true, message: "角色名称不能为空",}]}
                            >
                                <Input/>
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item
                                labelCol={{span: 4,}}
                                label={<Tooltip
                                    title="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)"><QuestionCircleOutlined/>权限字符</Tooltip>}
                                name="roleKey"
                                rules={[{required: true, message: "权限字符不能为空"}]}
                            >
                                <Input/>
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item
                                labelCol={{span: 4,}}
                                label="角色顺序"
                                name="roleSort"
                                rules={[
                                    {
                                        required: true, message: "角色顺序不能为空",
                                    }
                                ]}
                            >
                                <InputNumber min={0} max={10000} />
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item
                                labelCol={{span: 4,}}
                                label="状态"
                                name="status"
                            >
                                <Radio.Group>
                                    <Radio value={"0"}>正常</Radio>
                                    <Radio value={"1"}>停用</Radio>
                                </Radio.Group>
                            </Form.Item>
                        </Col>
                        <Col span={24}>

                            <Row>
                                <Col span={10}>
                                    <Form.Item
                                        labelCol={{span: 10,}}
                                        label="菜单权限"
                                        valuePropName="checked">
                                        <Checkbox>展开/折叠</Checkbox>
                                    </Form.Item>
                                </Col>
                                <Col span={6}>
                                    <Form.Item valuePropName="checked">
                                        <Checkbox>全选/全不选</Checkbox>
                                    </Form.Item>
                                </Col>
                                <Col span={6}>
                                    <Form.Item
                                        name="menuCheckStrictly"
                                        valuePropName="checked">
                                        <Checkbox onChange={onIsLeaf}>父子联动</Checkbox>
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Col>
                        <Col span={24}>
                            <Form.Item
                                labelCol={{span: 4,}}
                                label={' '}
                                name="menuIds">
                                <Tree
                                    checkStrictly={isLeaf}
                                    checkable
                                    onCheck={onCheck}
                                    defaultCheckedKeys={checkedKeys}
                                    checkedKeys={checkedKeys}
                                    defaultSelectedKeys={checkedKeys}
                                    treeData={roleOptions}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item
                                labelCol={{span: 4,}}
                                label="备注"
                                name="remark"
                            >
                                <Input.TextArea/>
                            </Form.Item>
                        </Col>

                        <Col span={24}>
                            <Form.Item
                                wrapperCol={{offset: 16, span: 8}}
                            >
                                <div className={styles.buttonClass}>
                                    <Button type="primary" htmlType="submit" onClick={handleSubmit}>确认</Button>
                                    <Button type="primary" onClick={handleCancel}>取消</Button>
                                </div>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Modal>

        </>
    )
};
export default EditorRoleView;
